#!/usr/bin/env python3
# coding=utf-8

import numpy as np
import random
import cv2
import skimage
from skimage import util as skutil
from skimage import io as skio, color as skclr

# 向图片中添加加性噪声


def addrandom_noise(image, prob=0.1):
    output = image   # 将原始图像数据拷贝至输出矩阵
    n = random.randint(1, 10000) + int(prob * 20000)
    for k in range(n - 500):
        a = random.randint(0, 100)
        i = random.randint(0, image.shape[0] - 1)
        j = random.randint(0, image.shape[1] - 1)
        output[i][j] = output[i][j] + a
    for k in range(n):
        a = random.randint(0, 100)
        i = random.randint(0, image.shape[0] - 1)
        j = random.randint(0, image.shape[1] - 1)
        output[i][j] = output[i][j] - a
    output = cv2.normalize(output, None, 0, 255, cv2.NORM_MINMAX)
    return output


if __name__ == "__main__":
    # ifile = 'data/Lena.bmp'
    ifile = 'data/雨伞-B.jpg'
    img = cv2.imread(ifile, cv2.IMREAD_GRAYSCALE)
    im_addnoise = addrandom_noise(img)
    cv2.imwrite('tmp/noised_umbr_add.jpg', im_addnoise)

    skimg = skio.imread(ifile)
    im_specklenoise = skutil.random_noise(skimg, mode='speckle', clip=True)
    skio.imsave('tmp/noised_umbr_speckle.jpg', im_specklenoise)
    im_gaussnoise = skutil.random_noise(skimg, mode='gaussian', clip=True)
    skio.imsave('tmp/noised_umbr_gaussian.jpg', im_gaussnoise)
    im_spnoise = skutil.random_noise(skimg, mode='s&p', amount=0.2, clip=True)
    skio.imsave('tmp/noised_umbr_sp.jpg', im_spnoise)
